<template>
	<view class="content">
		<view class="text-area">
			<text class="title">{{ title }}</text>
		</view>

		<view class="page-body-time">
			<text class="time-small">录音时间：{{recordTime}}</text>
			<text class="time-small">播放时间：{{playTime}}</text>
		</view>

		<view class="voice-btn-wrap">
			<nb-voice-record ref="recorder" @startRecord="start" @endRecord="end"
				@cancelRecord="cancel"></nb-voice-record>
		</view>

		<view class="page-body-buttons">
			<view class="page-body-button" @click="playVoice">
				<image src="../../static/play.png"></image>
			</view>
			<view class="page-body-button" @click="clear">
				<image src="../../static/trash.png"></image>
			</view>
		</view>
	</view>
</template>

<script>
	let music = null;
	export default {
		data() {
			return {
				title: 'Hello',
				uuid: '',
				recordedFilePath: null,
				recordTime: '00:00', // 录音的总时间，格式为分钟:秒
				playTime: '00:00', // 播放录音的当前时间
				recordTimer: null, // 用于录音的定时器
				playTimer: null, // 用于播放的定时器
				recordingType: '',
				isPlaying: false, // 用于跟踪录音是否正在播放
			};
		},
		onLoad(options) {
			console.log('Options received:', options);
			if (options.type) {
				this.recordingType = decodeURIComponent(options.type);
				console.log('Received grid name:', this.recordingType);
			} else {
				console.log('No grid name received');
			}
			if (options.uuid) {
				this.uuid = options.uuid;
				console.log('录音页面Received uuid:', this.uuid);
			} else {
				console.log('No uuid received');
			}
			music = uni.createInnerAudioContext();
			// 尝试下载录音文件
			this.downloadRecordedFile();
		},
		methods: {
			// 开始录音
			start() {
				this.title = '录音已开始';
				this.recordTime = '00:00';
				let totalSeconds = 0;
				this.recordTimer = setInterval(() => {
					totalSeconds++;
					let minutes = Math.floor(totalSeconds / 60);
					let seconds = totalSeconds % 60;

					let formattedMinutes = minutes < 10 ? '0' + minutes : minutes;
					let formattedSeconds = seconds < 10 ? '0' + seconds : seconds;

					this.recordTime = `${formattedMinutes}:${formattedSeconds}`;

					if (totalSeconds >= 60) {
						this.$refs.recorder.stopRecord();
					}
				}, 1000);
			},
			// 结束录音
			end(e) {
				this.title = '录音结束';
				clearInterval(this.recordTimer);
				this.recordTimer = null;
				console.log('end', e);
				this.recordedFilePath = e.tempFilePath;

				const key = `userRecording${this.uuid}${this.recordingType}`;
				uni.setStorageSync(key, this.recordedFilePath);

				uni.showToast({
					title: `录音已保存`,
					icon: 'success',
					duration: 2000
				});
				let message = {
					"msg": "update_rec"
				};
				let opts = {
					topic: 'LSY/app/' + this.uuid,
					message: JSON.stringify(message)
				};
				this.$mqttTool.publish(opts).then(res => {
					uni.showToast({
						title: '查找发送成功',
						icon: 'success',
						duration: 2000
					});
				}).catch(err => {
					uni.showToast({
						title: '消息发送失败',
						icon: 'none',
						duration: 2000
					});
				});
				this.uploadRecordedFile();
			},
			// 取消录音
			cancel() {
				this.title = '录音取消，停止录音';
				clearInterval(this.recordTimer);
				this.recordTimer = null;
				this.recordTime = '00:00';
			},
			// 播放录音
			playVoice() {
				if (!this.recordedFilePath || this.isPlaying) return;
				this.playTime = '00:00';
				let seconds = 0;
				this.isPlaying = true;
				music.src = this.recordedFilePath;
				music.play();
				music.onPlay(() => {
					this.title = '播放录音中...';
					this.playTimer = setInterval(() => {
						seconds++;
						this.playTime = `00:${seconds < 10 ? '0' + seconds : seconds}`;
					}, 1000);
				});
				music.onEnded(() => {
					clearInterval(this.playTimer);
					this.playTimer = null;
					this.playTime = '00:00';
					this.title = '播放结束';
					this.isPlaying = false;
				});
				music.onError((error) => {
					console.error('播放失败:', error);
					this.isPlaying = false;
				});
			},
			// 清除录音文件
			clear() {
				if (!this.recordedFilePath) return;
				uni.removeSavedFile({
					filePath: this.recordedFilePath,
					success: () => {
						this.title = '录音文件已删除';
						console.log('文件删除成功');
						this.recordedFilePath = null;
						this.recordTime = '00:00';
					},
					fail: (error) => {
						console.error('文件删除失败', error);
					}
				});
			},
			// 上传录音文件到服务器
			uploadRecordedFile() {
				const fileName = `${this.uuid}_${this.recordingType}.mp3`;
				uni.uploadFile({
					url: this.$baseUrl + '/upload/records',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'token': uni.getStorageSync('token')
					},
					filePath: this.recordedFilePath,
					name: 'mFile',
					formData: {
						'uuid': this.uuid,
						'newName': fileName
					},
					success: (uploadRes) => {
						console.log('上传成功:', uploadRes);
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					},
					fail: (uploadError) => {
						console.error('上传失败:', uploadError);
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						});
					}
				});
			},
			// 下载录音文件
			downloadRecordedFile() {
				const fileName = `${this.uuid}_${this.recordingType}.mp3`;
				uni.downloadFile({
					url: `${this.$baseUrl}/download/device/${this.uuid}/rec/` + fileName,
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'token': uni.getStorageSync('token')
					},
					success: (downloadRes) => {
						console.log('下载录音结果', downloadRes);
						if (downloadRes.statusCode === 200) {
							uni.saveFile({
								tempFilePath: downloadRes.tempFilePath,
								success: (saveFileRes) => {
									this.recordedFilePath = saveFileRes.savedFilePath;
									const key = `userRecording${this.uuid}${this.recordingType}`;
									uni.setStorageSync(key, this.recordedFilePath);
									console.log(this.recordedFilePath);
									this.title = '已加载已有录音，点击可播放';
									uni.showToast({
										title: '加载成功',
										icon: 'success'
									});
								},
								fail: (err) => {
									console.log('保存文件失败', err);
									uni.showToast({
										title: '保存文件失败，请重试',
										icon: 'none'
									});
								}
							});
						} else {
							console.log('下载失败', downloadRes);
							uni.showToast({
								title: '没有找到录音文件，请录音',
								icon: 'none'
							});
						}
					}
				});
			}
		}
	}
</script>


<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 50rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		margin-top: 20rpx;
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 28rpx;
		color: #8f8f94;
	}

	.voice-btn-wrap {
		width: 100%;
		position: fixed;
		bottom: 50rpx;
		left: 0;
		display: flex;
		justify-content: center;
	}

	image {
		width: 150rpx;
		height: 150rpx;
	}

	.page-body-wrapper {
		justify-content: space-between;
		flex-grow: 1;
		margin-bottom: 400rpx;
	}

	.page-body-time {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.time-big {
		font-size: 60rpx;
		margin: 20rpx;
	}

	.time-small {
		margin: 10rpx;
		font-size: 40rpx;
	}

	.page-body-buttons {
		margin-top: 60rpx;
		display: flex;
		justify-content: space-around;
	}

	.page-body-button {
		width: 250rpx;
		text-align: center;
	}

	.button-stop-record {
		width: 110rpx;
		height: 110rpx;
		border: 20rpx solid #fff;
		background-color: #f55c23;
		border-radius: 100rpx;
		margin: 0 auto;
	}
</style>